上章說的問題,其實官方已經給解決方式
import React, {useContext} from 'react'
const texts = {
r1: {
name: "react",
text: "你好"
},
r2: {
name: "react2",
text: "你好2"
},
r3: {
name: "react3",
text: "你好3"
},
};
const texts_t = React.createContext(texts);
function ThemedButton() {
const tt = useContext(texts_t);
return (
<button >
{tt.name} {tt.text}
</button>
);
}
function Text1() {
return (
<texts_t.Provider value={texts.r1}>
<ThemedButton />
</texts_t.Provider>
);
}
function Text2() {
return (
<texts_t.Provider value={texts.r2}>
<ThemedButton />
</texts_t.Provider>
);
}
function Text3() {
return (
<texts_t.Provider value={texts.r3}>
<ThemedButton />
</texts_t.Provider>
);
}
export default function App() {
return (
<div>
<Text1/>
<Text2/>
<Text3/>
</div>
);
}
將值單獨提出來,這樣就方便很多,可是這樣這樣寫組件還是太過複雜,重複性太多,一樣不好
於是在改變
import React, {useContext} from 'react'
const texts = {
r1: {
name: "react",
text: "你好"
},
r2: {
name: "react2",
text: "你好2"
},
r3: {
name: "react3",
text: "你好3"
},
};
const texts_t = React.createContext(texts);
function ThemedButton() {
const tt = useContext(texts_t);
return (
<button >
{tt.name} {tt.text}
</button>
);
}
const Text1= ({ text }) => {
return (
<texts_t.Provider value={text}>
<ThemedButton />
</texts_t.Provider>
);
}
export default function App() {
return (
<div>
<Text1 text={texts.r1}/>
<Text1 text={texts.r2}/>
<Text1 text={texts.r3}/>
</div>
);
}
這樣寫就方便很多,最像原先的props,這也是我在第16天寫的方式
https://ithelp.ithome.com.tw/articles/10238010
組件與props的應用